package org.example.file;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileExample {
    public static void main(String[] args) {
        Path path = Paths.get("file:///C:/Users/JohnConnor/Documents/Downloads/catalina.out");
        String zipName = "example.zip";
        try {
            /*zipSingleFile(path,zipName);*/
            zipSingleFileNIO(path,zipName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void zipSingleFile(Path source,String zipFileName) throws IOException {
        if (!Files.isRegularFile(source)) {
            System.err.println("please provide a file.");
            return;
        }
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName))) {
            try (FileInputStream fileInputStream = new FileInputStream(source.toFile())) {
                ZipEntry zipEntry = new ZipEntry(source.getFileName().toString());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer,0,len);
                }
                zipOutputStream.closeEntry();
            }
        }
    }

    static void zipSingleFileNIO(Path source,String zipFileName) throws IOException {
        if (!Files.isRegularFile(source)) {
            System.err.println("please provide a file.");
            return;
        }

        Map<String,String> env = new HashMap<>();
        env.put("create","true");

        URI uri = URI.create("jar:file:C:\\Users\\JohnConnor\\Documents\\Downloads\\" + zipFileName);
        try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
            Path path = zipfs.getPath(source.getFileName().toString());
            Files.copy(source,path,StandardCopyOption.REPLACE_EXISTING);

        }
    }
}
